package com.tanhua.server.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.commons.template.OssTemplate;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mogo.Video;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.VideoVO;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class VideoService {


    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Reference
    private VideoApi videoApi;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Reference
    private UserInfoApi userInfoApi;
    @Autowired
    private VideoMQService videoMQService;



    //发布视频
    public ResponseEntity saveVideo(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        //视频封面图上传到阿里云
        String imagePath = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());

        //视频上传到FastDFS
        //文件名
        String videoName = videoFile.getOriginalFilename();
        //文件后缀
        String videoSuffix = videoName.substring(videoName.lastIndexOf(".")+1);
        //路径
        StorePath storePath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), videoSuffix, null);
        //路径
        String videoPath = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();

        //封装Video对象
        Video video = new Video();
        video.setUserId(UserHolder.getUserId());
        video.setPicUrl(imagePath);
        video.setVideoUrl(videoPath);

        //保存到mongo
        String videoId= videoApi.save(video);
        //发送消息
        videoMQService.saveVideoMessage(videoId);
        return ResponseEntity.ok(null);


    }
    /**
     * 页码1，查询10条，key=1_10
     */
    //小视频--视频列表
    public ResponseEntity findVideoList(int page, int pagesize) {
        //查询视频列表  优先从Redis里找
   PageResult<Video> pageResult =findVideoFromRedis(page,pagesize);
        if (pageResult == null) {
            pageResult=videoApi.findVideoList(page,pagesize);
        }

        //把结果转换成vo
        List<Video> videoList = pageResult.getItems();
        List<VideoVO> voList = new ArrayList<>();
        for (Video video : videoList) {
            VideoVO videoVO = new VideoVO();
            //把小视频信息封装到vo里
            BeanUtils.copyProperties(video,videoVO);
            videoVO.setId(video.getId().toHexString());
            videoVO.setCover(video.getPicUrl());
            videoVO.setSignature(video.getText());

            //把发布者信息封装到vo里
            UserInfo userInfo = userInfoApi.findById(video.getUserId());
            videoVO.setUserId(userInfo.getId());
            videoVO.setAvatar(userInfo.getAvatar());
            videoVO.setNickname(userInfo.getNickname());
            //当前用户是否点赞了此视频
            Boolean hasLike = redisTemplate.hasKey("video_like_" + UserHolder.getUserId() + "_" + video.getId().toHexString());
            videoVO.setHasLiked(hasLike?1:0);
            //当前用户是否关注了此视频作者
            Boolean hasFocus = redisTemplate.hasKey("follow_user_" + UserHolder.getUserId() + "_" + video.getId().toHexString());
            videoVO.setHasFocus(hasFocus?1:0);

            voList.add(videoVO);
        }
          //封装返回值
        PageResult<VideoVO> voPageResult = new PageResult<>();
          BeanUtils.copyProperties(pageResult,voPageResult);
        voPageResult.setItems(voList);
          return ResponseEntity.ok(voPageResult);

    }
    //查找视频列表  优先从redis中找
    private PageResult<Video> findVideoFromRedis(int page, int pagesize) {
        //从redis里找数据
        String vidStr = redisTemplate.opsForValue().get("QUANZI_VIDEO_RECOMMEND_" + UserHolder.getUserId());
        if (vidStr==null){
            return  null;
        }
        //计算总数量
        String[] vidArry = vidStr.split(",");
        int count=vidArry.length;

        //计算分了多少页
        int pages= (int) Math.ceil(count*1.0/page);
        //查询视频列表
        if (page<pages){
            int start=(page-1)*pagesize;
            int end=start+pagesize;
            if (end>count){
                end=count;
            }
            ArrayList<Long > vidList = new ArrayList<>();
            for (int i=start;i<end;i++){
                long vid = Long.parseLong(vidArry[i]);
                vidList.add(vid);
            }
        List<Video>  videoList = videoApi.findVideoByVids(vidList);
            return new PageResult<>(count,pages,page,pagesize,videoList);

        }
        return new PageResult<>();
    }

    //小视频--关注
    public ResponseEntity followUser(Long followUserId) {
        //获取当前用户Id
        Long userId = UserHolder.getUserId();
        //保存到MongoDB
        videoApi.followUser(userId,followUserId);
        //缓存到redis，记录当前用户已关注了此用户
        redisTemplate.opsForValue().set("follow_user_"+userId+"_"+followUserId,"1");
        return ResponseEntity.ok(null);
    }


    //小视频--取消关注
    public ResponseEntity disFollowUser(Long followUserId) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //取消关注
        videoApi.disFollowUser(userId,followUserId);
        //删除缓存 删除当前用户对此用户的关注记录
        redisTemplate.delete("follow_user_"+userId+"_"+followUserId);
        return ResponseEntity.ok(null);
    }

}
